package com.qf.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.Properties;

@Component
@PropertySource("classpath:db.properties")
public class MyBatisConfig {

    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean
    public DataSource getDs(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);

        return ds;
    }

    @Bean("transactionManager")
    public DataSourceTransactionManager getDSTM(DataSource ds){
        DataSourceTransactionManager dstm = new DataSourceTransactionManager();
        dstm.setDataSource(ds);
        return dstm;
    }

    @Bean
    public static MapperScannerConfigurer getMSC(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.qf.dao");
        return msc;
    }

    @Bean
    public SqlSessionFactoryBean getSSFB(DataSource ds){
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        ssfb.setDataSource(ds);

        //设置实体包别名
        ssfb.setTypeAliasesPackage("com.qf.entity");

        //设置分页插件
        Interceptor interceptor = new PageInterceptor();
        Properties pro = new Properties();
        pro.setProperty("helperDialect","mysql");
        pro.setProperty("reasonable","true");
        interceptor.setProperties(pro);
        ssfb.setPlugins(interceptor);

        return ssfb;
    }
}
